import numpy as np
import torch
from torch.utils import data
from d2l import torch as d2l
from stage01.linearRegression01 import batch_size, data_iter, num_epochs

true_w = torch.tensor([2, -3.4])
true_b = 4.2

features, labels = d2l.synthetic_data(true_w, true_b, 1000)

#调用框架中现有的API来读取数据
def load_array(data_arrays, batch_size, is_train = True):
    """构造一个PyTorch数据迭代器"""
    dataset = data.TensorDataset(*data_arrays)
    #DataLoader是一个函数每次从数据集中挑选batch_size个数出来
    return data.DataLoader(dataset, batch_size, shuffle=is_train)

batch_size = 10
data_iter = load_array((features, labels), batch_size)

#通过next将其转成一个python的x和y
next(iter(data_iter))

# 使用框架的预定义好的层，这里的nn就是new on network的缩写
from torch import nn
net = nn.Sequential(nn.Linear(2, 1))

#初始化模型参数
net[0].weight.data.normal_(0, 0.01)
net[0].bias.data.fill_(0)

#使用均方误差使用的是MSELoss类，也称为平方范数
loss = nn.MSELoss()
#实例化SGD实例
trainer = torch.optim.SGD(net.parameters(), lr=0.03)

#训练过程代码与我们从零开始实现时所做的非常相似
num_epochs = 3
for epoch in range(num_epochs):
    for X, y in data_iter:
        l = loss(net(X), y)
        trainer.zero_grad()
        l.backward()
        trainer.step()#调用step这个函数来进行一次模型的更新
    l = loss(net(features), labels)
    print(f'epoch {epoch + 1}, loss {l:f}')